/*
    Copyright: Octavian Marius Chincisan 2012.
    global working set.
*/

#include <memory>
#include "main.h"
#include "database.h"
#include "site.h"
#include "wcurl.h"
#include "config.h"
#include "glb.h"

//-----------------------------------------------------------------------------
mutex               glb::_m;
set<string>         glb::_uris;
deque<uripage*>     glb::_q;

//-----------------------------------------------------------------------------
bool glb::add(const string& uri)
{
    AutoLock __l(&_m);

    set<string>::const_iterator f = _uris.find(uri);
    if(f == _uris.end() )
    {
        GLOGD( "#---<<{{" << uri<<"}}");
        _uris.insert(uri);
        return true;
    }
    return false;
}

//-----------------------------------------------------------------------------
void glb::remove(const string& uri)
{
    AutoLock __l(&_m);

    set<string>::const_iterator f = _uris.find(uri);
    if(f != _uris.end() )
    {
         GLOGD("#--->>{{" << uri<<"}}");
        _uris.erase(uri);
    }

}

//-----------------------------------------------------------------------------
bool glb::enqueue( uripage* uri)
{
    AutoLock __l(&_m);
    if(add(uri->_uri))
    {
        glb::_q.push_back(uri);
        GLOGT( "Q---<<{{" << uri->_uri <<"}}");
        return true;
    }
    return false;
}

//-----------------------------------------------------------------------------
uripage* glb::dequeue()
{
    AutoLock __l(&_m);
    if(_q.size())
    {
        uripage* rv = _q.front();
        glb::_q.pop_front();
        GLOGT("Q--->>{{" << rv->_uri << "}}");
        return rv;
    }
    return 0;
}

//-----------------------------------------------------------------------------
void glb::add_site(mysqlcls* db, mutex* m, const char* addr)
{
    if(addr[0]==0)
        return;
    ref_count<wsite>    psite(new wsite(addr, db, m));
    psite->_z_id = db->sess_id();

    string uri = psite->_hargs["sn"];
    uripage* page = new uripage(psite, uri);
    if(!glb::enqueue(page))
    {
        delete page;
    }
}

//-----------------------------------------------------------------------------
bool glb::inset(const string& uri)
{
    AutoLock __l(&_m);
    set<string>::const_iterator f = _uris.find(uri);
    return f != _uris.end();
}

//-----------------------------------------------------------------------------
void glb::wset(string& s)
{
     AutoLock __l(&_m);
     set<string>::iterator b = _uris.begin();
     for(; b!= _uris.end(); ++b)
     {
         s += *b + "\n";
     }
}
